<?php

namespace app\library;

/**
 * 数据加密解密工具
 * Class Crypt
 * @package app\library
 */
class Crypt
{
    /**
     * UTF8字符串加密
     * @param string $text 待加密文本
     * @return string
     */
    public static function encode($text)
    {
        list($chars, $length) = ['', strlen($content = iconv('UTF-8', 'GBK//TRANSLIT', $text))];
        for ($i = 0; $i < $length; $i++) $chars .= str_pad(base_convert(ord($content[$i]), 10, 36), 2, 0, 0);
        return $chars;
    }

    /**
     * UTF8字符串解密
     * @param string $text 待加密文本
     * @return string
     */
    public static function decode($text)
    {
        $chars = '';
        foreach (str_split($text, 2) as $char) {
            $chars .= chr(intval(base_convert($char, 36, 10)));
        }
        return iconv('GBK//TRANSLIT', 'UTF-8', $chars);
    }
    
    /**
     * Base64Url 安全编码
     * @param string $text 待加密文本
     * @return string
     */
    public static function enSafe64($text)
    {
        return rtrim(strtr(base64_encode($text), '+/', '-_'), '=');
    }

    /**
     * Base64Url 安全解码
     * @param string $text 待解密文本
     * @return string
     */
    public static function deSafe64($text)
    {
        return base64_decode(str_pad(strtr($text, '-_', '+/'), strlen($text) % 4, '='));
    }
    
}
